//
// Created by denglibin on 2021/3/26.
// 简单动画
#include <SDL.h>
#define WIN_WIDTH 600
#define WIN_HEIGHT 400
static SDL_Window * win; //窗口
static SDL_Surface * winSurface; //窗口的surface
static int run  = 1; // 状态 是否运行

static int red_rect_x = 0; //红色方块的x坐标
/**
 * 绘制
 */
static void draw(){
    //矩形
    struct SDL_Rect  r = {0, 0, WIN_WIDTH, WIN_HEIGHT};
    //用矩形填充winSurface
    SDL_FillRect(winSurface, &r, 0xFF00AA00);

    //矩形
    struct SDL_Rect redR = {red_rect_x++, 0, 200, 200};
    //填充
    SDL_FillRect(winSurface, &redR, 0xFFAA0000);

    //更新winSurface
    SDL_UpdateWindowSurface(win);
}

/**
 * 事件循环
 */
static void eventLoop(){
    SDL_Event  event;
    while (run)
    {//主消息循环
        draw(); //循环绘制
        //SDL_WaitEvent(&event); //阻塞
        SDL_PollEvent(&event);
        switch (event.type)
        {
            //用户从菜单要求退出程序
            case SDL_QUIT:
                run = 0;
                break;
            default:
                break;
        }
        SDL_Delay(20); //休眠20ms， 刷新频率 大概50帧/s （前提是循环体中不会有耗时操作）
    }
    SDL_Quit();
}


/**
 * 创建显示窗口
 * @return
 */
static int showWindow(){
    //初始化，成功返回0
    if (SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("Can not init video %s\n", SDL_GetError());
        return 1;
    }
    win = SDL_CreateWindow("Hello World",
                           SDL_WINDOWPOS_CENTERED,
                           SDL_WINDOWPOS_CENTERED,
                           WIN_WIDTH,
                           WIN_HEIGHT,
                           SDL_WINDOW_SHOWN
    );
    if (win == NULL) {
        SDL_Log("Can not create window %s\n", SDL_GetError());
        return 2;
    }
    winSurface = SDL_GetWindowSurface(win);
    return 0;

}

/**
 * 清理
 */
static void clean(){
    SDL_DestroyWindow(win);
}
int main2_5(int argc, char* argv[]){
    if (showWindow()){
        exit(1);
    }
    eventLoop();
    clean();
}

